import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../utils/keyboard_utils.dart';

// Riverpod Providers
final counterProvider = StateProvider<int>((ref) => 0);
final nameProvider = StateProvider<String>((ref) => 'Guest');

// 计算属性Provider
final doubleCounterProvider = Provider<int>((ref) {
  final count = ref.watch(counterProvider);
  return count * 2;
});

// 异步Provider示例
final userDataProvider = FutureProvider<String>((ref) async {
  await Future.delayed(const Duration(seconds: 2));
  return '用户数据已加载';
});

/// Flutter状态管理示例
class StateManagementExample extends StatefulWidget {
  const StateManagementExample({super.key});

  @override
  State<StateManagementExample> createState() => _StateManagementExampleState();
}

class _StateManagementExampleState extends State<StateManagementExample> {
  String _selectedDemo = 'setstate';

  @override
  Widget build(BuildContext context) {
    return DismissKeyboardScaffold(
      appBar: AppBar(title: const Text('Flutter 状态管理'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
      child: Column(
        children: [
          // 状态管理方式选择器
          Container(
            padding: const EdgeInsets.all(8),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Wrap(
                spacing: 8,
                children: [
                  ChoiceChip(
                    label: const Text('setState'),
                    selected: _selectedDemo == 'setstate',
                    onSelected: (selected) {
                      setState(() => _selectedDemo = 'setstate');
                    },
                  ),
                  ChoiceChip(
                    label: const Text('Riverpod'),
                    selected: _selectedDemo == 'riverpod',
                    onSelected: (selected) {
                      setState(() => _selectedDemo = 'riverpod');
                    },
                  ),
                  ChoiceChip(
                    label: const Text('状态提升'),
                    selected: _selectedDemo == 'lift',
                    onSelected: (selected) {
                      setState(() => _selectedDemo == 'lift');
                    },
                  ),
                ],
              ),
            ),
          ),
          const Divider(height: 1),
          Expanded(
            child: SingleChildScrollView(padding: const EdgeInsets.all(16), child: _buildSelectedDemo()),
          ),
        ],
      ),
    );
  }

  Widget _buildSelectedDemo() {
    switch (_selectedDemo) {
      case 'setstate':
        return _buildSetStateDemo();
      case 'riverpod':
        return const _RiverpodDemo();
      case 'lift':
        return _buildLiftStateDemo();
      default:
        return const SizedBox();
    }
  }

  Widget _buildSetStateDemo() {
    return const _SetStateCounter();
  }

  Widget _buildLiftStateDemo() {
    return const _LiftStateDemo();
  }
}

// setState示例
class _SetStateCounter extends StatefulWidget {
  const _SetStateCounter();

  @override
  State<_SetStateCounter> createState() => _SetStateCounterState();
}

class _SetStateCounterState extends State<_SetStateCounter> {
  int _counter = 0;

  void _increment() {
    setState(() {
      _counter++;
    });
  }

  void _decrement() {
    setState(() {
      _counter--;
    });
  }

  void _reset() {
    setState(() {
      _counter = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const Text('setState（基础状态管理）', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
        const SizedBox(height: 8),
        const Text('最简单的状态管理方式，适合简单的局部状态。'),
        const SizedBox(height: 16),

        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                const Text('计数器示例', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                const SizedBox(height: 16),
                Text('$_counter', style: Theme.of(context).textTheme.displayLarge),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    FilledButton.icon(onPressed: _decrement, icon: const Icon(Icons.remove), label: const Text('减少')),
                    const SizedBox(width: 8),
                    FilledButton.icon(onPressed: _increment, icon: const Icon(Icons.add), label: const Text('增加')),
                    const SizedBox(width: 8),
                    OutlinedButton(onPressed: _reset, child: const Text('重置')),
                  ],
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('代码示例', style: TextStyle(fontWeight: FontWeight.bold)),
                const SizedBox(height: 8),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
                  child: const Text('''class _CounterState extends State<Counter> {
  int _counter = 0;

  void _increment() {
    setState(() {
      _counter++; // 修改状态
    }); // setState会触发rebuild
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('\$_counter'),
        ElevatedButton(
          onPressed: _increment,
          child: Text('增加'),
        ),
      ],
    );
  }
}''', style: TextStyle(fontFamily: 'monospace', fontSize: 12)),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        Card(
          color: Colors.blue.shade50,
          child: const Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('setState特点：', style: TextStyle(fontWeight: FontWeight.bold)),
                SizedBox(height: 8),
                Text('✓ 简单直观'),
                Text('✓ 适合局部状态'),
                Text('✓ 无额外依赖'),
                SizedBox(height: 8),
                Text('✗ 难以跨组件共享'),
                Text('✗ 容易重建整个Widget树'),
                Text('✗ 难以测试'),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

// Riverpod示例
class _RiverpodDemo extends ConsumerWidget {
  const _RiverpodDemo();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final counter = ref.watch(counterProvider);
    final doubleCounter = ref.watch(doubleCounterProvider);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const Text('Riverpod（推荐的状态管理）', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
        const SizedBox(height: 8),
        const Text('Riverpod是现代化的状态管理方案，类型安全、易测试。'),
        const SizedBox(height: 16),

        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                const Text('基础Provider示例', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                const SizedBox(height: 16),
                Text('计数: $counter', style: Theme.of(context).textTheme.headlineLarge),
                Text('双倍: $doubleCounter', style: Theme.of(context).textTheme.headlineSmall),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    FilledButton.icon(
                      onPressed: () {
                        ref.read(counterProvider.notifier).state--;
                      },
                      icon: const Icon(Icons.remove),
                      label: const Text('减少'),
                    ),
                    const SizedBox(width: 8),
                    FilledButton.icon(
                      onPressed: () {
                        ref.read(counterProvider.notifier).state++;
                      },
                      icon: const Icon(Icons.add),
                      label: const Text('增加'),
                    ),
                    const SizedBox(width: 8),
                    OutlinedButton(
                      onPressed: () {
                        ref.read(counterProvider.notifier).state = 0;
                      },
                      child: const Text('重置'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('代码示例', style: TextStyle(fontWeight: FontWeight.bold)),
                const SizedBox(height: 8),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
                  child: const Text('''// 1. 定义Provider
final counterProvider = StateProvider<int>((ref) => 0);

// 2. 计算属性Provider
final doubleCounterProvider = Provider<int>((ref) {
  final count = ref.watch(counterProvider);
  return count * 2;
});

// 3. 使用ConsumerWidget
class MyWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 读取状态
    final counter = ref.watch(counterProvider);
    
    return Column(
      children: [
        Text('\$counter'),
        ElevatedButton(
          onPressed: () {
            // 修改状态
            ref.read(counterProvider.notifier).state++;
          },
          child: Text('增加'),
        ),
      ],
    );
  }
}''', style: TextStyle(fontFamily: 'monospace', fontSize: 11)),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        // 异步Provider示例
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('FutureProvider示例', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                const SizedBox(height: 12),
                Consumer(
                  builder: (context, ref, child) {
                    final asyncValue = ref.watch(userDataProvider);

                    return asyncValue.when(
                      data: (data) => Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(color: Colors.green.shade50, borderRadius: BorderRadius.circular(8)),
                        child: Row(
                          children: [
                            const Icon(Icons.check_circle, color: Colors.green),
                            const SizedBox(width: 8),
                            Text(data),
                          ],
                        ),
                      ),
                      loading: () => const Center(child: CircularProgressIndicator()),
                      error: (error, stack) => Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(color: Colors.red.shade50, borderRadius: BorderRadius.circular(8)),
                        child: Text('错误: $error'),
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        Card(
          color: Colors.purple.shade50,
          child: const Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Riverpod优势：', style: TextStyle(fontWeight: FontWeight.bold)),
                SizedBox(height: 8),
                Text('✓ 编译时安全'),
                Text('✓ 易于测试'),
                Text('✓ 支持异步'),
                Text('✓ 自动依赖管理'),
                Text('✓ 无BuildContext限制'),
                Text('✓ 支持状态组合'),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

// 状态提升示例
class _LiftStateDemo extends StatefulWidget {
  const _LiftStateDemo();

  @override
  State<_LiftStateDemo> createState() => _LiftStateDemoState();
}

class _LiftStateDemoState extends State<_LiftStateDemo> {
  String _sharedText = 'Hello';

  void _updateText(String newText) {
    setState(() {
      _sharedText = newText;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const Text('状态提升（Lifting State Up）', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
        const SizedBox(height: 8),
        const Text('当多个子组件需要共享状态时，将状态提升到共同的父组件。'),
        const SizedBox(height: 16),

        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('共享状态演示', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                const SizedBox(height: 12),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(color: Colors.blue.shade50, borderRadius: BorderRadius.circular(8)),
                  child: Text('共享文本: $_sharedText', style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                ),
                const SizedBox(height: 16),
                _InputChild(onTextChanged: _updateText),
                const SizedBox(height: 12),
                _DisplayChild(text: _sharedText),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('代码示例', style: TextStyle(fontWeight: FontWeight.bold)),
                const SizedBox(height: 8),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
                  child: const Text('''// 父组件管理状态
class Parent extends StatefulWidget {
  @override
  State<Parent> createState() => _ParentState();
}

class _ParentState extends State<Parent> {
  String _sharedText = 'Hello';

  void _updateText(String newText) {
    setState(() {
      _sharedText = newText;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 将状态和回调传给子组件
        InputChild(onTextChanged: _updateText),
        DisplayChild(text: _sharedText),
      ],
    );
  }
}

// 子组件1：输入
class InputChild extends StatelessWidget {
  final Function(String) onTextChanged;
  
  @override
  Widget build(BuildContext context) {
    return TextField(
      onChanged: onTextChanged,
    );
  }
}

// 子组件2：显示
class DisplayChild extends StatelessWidget {
  final String text;
  
  @override
  Widget build(BuildContext context) {
    return Text(text);
  }
}''', style: TextStyle(fontFamily: 'monospace', fontSize: 11)),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        Card(
          color: Colors.orange.shade50,
          child: const Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('状态提升原则：', style: TextStyle(fontWeight: FontWeight.bold)),
                SizedBox(height: 8),
                Text('1. 找到共同的父组件'),
                Text('2. 在父组件中管理状态'),
                Text('3. 通过props传递状态'),
                Text('4. 通过回调函数修改状态'),
                SizedBox(height: 8),
                Text('注意：深层嵌套时考虑使用Provider/Riverpod', style: TextStyle(fontStyle: FontStyle.italic)),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

// 输入子组件
class _InputChild extends StatelessWidget {
  const _InputChild({required this.onTextChanged});

  final Function(String) onTextChanged;

  @override
  Widget build(BuildContext context) {
    return TextField(
      decoration: const InputDecoration(labelText: '输入文本', border: OutlineInputBorder()),
      onChanged: onTextChanged,
    );
  }
}

// 显示子组件
class _DisplayChild extends StatelessWidget {
  const _DisplayChild({required this.text});

  final String text;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.green.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.green),
      ),
      child: Row(
        children: [
          const Icon(Icons.display_settings, color: Colors.green),
          const SizedBox(width: 8),
          Expanded(
            child: Text('显示组件接收到: $text', style: const TextStyle(fontWeight: FontWeight.bold)),
          ),
        ],
      ),
    );
  }
}
